package com.meida.module.bus.provider.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.security.OpenHelper;
import com.meida.common.security.OpenUser;
import com.meida.common.springmvc.base.BaseController;
import com.meida.module.bus.client.entity.BusReceiptDeliveryRecord;
import com.meida.module.bus.client.entity.BusReceiptDeliveryReq;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.service.BusRecDeliReqConfService;
import com.meida.module.bus.provider.service.BusRecDeliReqService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 材料员领料确认
 *
 * @author flyme
 * @date 2020-12-02Ser
 */
@RestController
@RequestMapping("/bus/recDeliReqConf/")
public class BusRecDeliReqConfController extends BaseController<BusRecDeliReqService, BusReceiptDeliveryReq> {

    @Autowired
    private PmsApiUtil pmsApiUtil;

    @ApiOperation(value = "预留发货记录表-分页列表", notes = "预留发货记录表分页列表")
    @GetMapping(value = "page")
    public ResultBody pageList(@RequestParam(required = false) Map params) {
        return bizService.pageList(params);
    }

    @ApiOperation(value = "预留发货记录表-列表", notes = "预留发货记录表列表")
    @GetMapping(value = "list")
    public ResultBody list(@RequestParam(required = false) Map params) {
        return bizService.listEntityMap(params);
    }

    @ApiOperation(value = "预留发货记录表-添加", notes = "添加预留发货记录表")
    @PostMapping(value = "save")
    public ResultBody save(@RequestBody Map params) throws Exception {
        StringBuffer errDetail = new StringBuffer();
        String postDateStr = String.valueOf(params.get("postDate"));
        String cerDateStr = String.valueOf(params.get("cerDate"));
        String cerTxtStr = String.valueOf(params.get("cerTxt"));
        if (StrUtil.isEmpty(postDateStr) || StrUtil.isEmpty(cerDateStr) || StrUtil.isEmpty(cerTxtStr)) {
            if (StrUtil.isEmpty(postDateStr)) {
                errDetail.append("过账日期为空");
            }
            if (StrUtil.isEmpty(cerDateStr)) {
                errDetail.append("，凭证日期为空");
            }
            if (StrUtil.isEmpty(cerTxtStr)) {
                errDetail.append("，抬头文本为空");
            }
            errDetail.append(errDetail.toString());
            return ResultBody.failed(errDetail.toString());
        }

        List<String> selectIdsStri = (List<String>) params.get("selectIds");
        List<Long> selectIdsList = Lists.newArrayList();
        selectIdsStri.stream().forEach(idO -> {
            selectIdsList.add(Long.valueOf(idO));
        });

        List<BusReceiptDeliveryReq> busReceiptDeliveryReqs = (List<BusReceiptDeliveryReq>) bizService.listByIds(selectIdsList);

        Collection<BusReceiptDeliveryReq> filterRecords =
            busReceiptDeliveryReqs.stream().filter(recordO -> StrUtil.isEmpty(recordO.getLgort())
            ).collect(Collectors.toList());
        if (0 < filterRecords.size()) {
            StringBuffer errBuf = new StringBuffer();
            filterRecords.stream().forEach(errRecord->{
                StringBuffer errDetail2 = new StringBuffer();
                errDetail2.append("预留号：" + errRecord.getReserveNo());
                errDetail2.append("，预留行号：" + errRecord.getReserveRow());
                if(StrUtil.isEmpty(errRecord.getLgort())) {
                    errDetail2.append("，库位为空");
                }
                errBuf.append(errDetail2.toString());
            });

            return ResultBody.failed(errBuf.toString());
        }
        BusReceiptDeliveryReq header = busReceiptDeliveryReqs.get(0);
        Integer ver = pmsApiUtil.getLastVer(header.getProjectId(), 0) ? ApiConstants.VER_100 : ApiConstants.VER_200;
        OpenUser user = OpenHelper.getUser();
        busReceiptDeliveryReqs.stream().forEach(updObj -> {
            updObj.setBudat(DateUtil.parseDate(postDateStr));
            updObj.setBldat(DateUtil.parseDate(cerDateStr));
            updObj.setBktxt(cerTxtStr);
            // A07：发料，A03：取消发料_SAP
            updObj.setAction("A07");
//            updObj.setSyncStatus(ApiConstants.REC_DELIVERY_FINISH);
            updObj.setDelFlg(ApiConstants.DEL_OFF);
            updObj.setConfUserId(user.getUserId());
            updObj.setConfUserName(user.getUsername());
            updObj.setVer(String.valueOf(ver));
        });
        Boolean syncRs = bizService.syncSap(busReceiptDeliveryReqs);
        // 出库成功
        if(syncRs) {
            busReceiptDeliveryReqs.stream().forEach(receiptObj->{
                receiptObj.setLgort("");
                receiptObj.setDeliveryNumThis(BigDecimal.ZERO);
            });
            bizService.updateBatchById(busReceiptDeliveryReqs);
            // 1：200版之前，出库数量 * 预算成本单价_主材价 = 产值
            // 2：200版之后，出库数量 * 预算成本单价_主材价【SRM最新同步数据_采购实际购买价格（最近一次购买价格）】 = 产值

        }

//        List<BusReceiptDeliveryRecordBack> bkRecords = Lists.newArrayList();
//        busReceiptDeliveryRecords.stream().forEach(recordObj->{
//            BusReceiptDeliveryRecordBack bkObj = new BusReceiptDeliveryRecordBack();
//            BeanUtil.copyProperties(recordObj, bkObj);
//            bkObj.setCharOffCountCan(recordObj.getRecNumThis());
//            bkObj.setStatus(ApiConstants.REC_BK_DELIVERY_INT);
//            bkRecords.add(bkObj);
//        });
//        bkservice.saveBatch(bkRecords);
        return ResultBody.msg("提交成功");
    }

    @ApiOperation(value = "预留发货记录表-更新", notes = "更新预留发货记录表")
    @PostMapping(value = "update")
    public ResultBody update(@RequestBody(required = false) List<BusReceiptDeliveryReq> reqS) {
        List<BusReceiptDeliveryRecord> recordS = Lists.newArrayList();
        reqS.stream().forEach(reqObj->{
            BusReceiptDeliveryReq busReceiptDeliveryReq = bizService.getById(reqObj.getRecDecId());
            // 可出库数量
            // 本次出库数量为0时，则冲销掉之前的出库数量
            if(BigDecimal.ZERO.equals(reqObj.getDeliveryNumThis())) {
                reqObj.setAvailableQty(NumberUtil.add(busReceiptDeliveryReq.getAvailableQty(), busReceiptDeliveryReq.getDeliveryNumThis()));
            } else {
                reqObj.setAvailableQty(NumberUtil.sub(busReceiptDeliveryReq.getAvailableQty(), reqObj.getDeliveryNumThis()));
            }
        });

        // 更新材料申请
        bizService.updateBatchById(reqS);

        return ResultBody.msg("提交成功");
    }

    @ApiOperation(value = "预留发货记录表-删除", notes = "删除预留发货记录表")
    @PostMapping(value = "remove")
    public ResultBody remove(@RequestParam(required = false) Map params) {
        return bizService.delete(params);
    }

    @ApiOperation(value = "预留发货记录表-详情", notes = "预留发货记录表详情")
    @GetMapping(value = "get")
    public ResultBody get(@RequestParam(required = false) Map params) {
        return bizService.get(params);
    }

    /**
     * 导出预留发货记录表统计
     *
     * @param params
     * @param request
     * @param response
     */
    @PostMapping(value = "export")
    public void export(@RequestParam(required = false) Map params, HttpServletRequest request, HttpServletResponse response) {
        bizService.export(params, request, response, "预留发货记录表统计", "预留发货记录表统计表");
    }


    @ApiOperation(value = "预留发货记录表-请求驳回", notes = "请求驳回")
    @PostMapping(value = "reqCancel")
    public ResultBody reqCancel(@RequestBody Long selectIds[]) {
        bizService.reqCancel(selectIds);
        return ResultBody.msg("提交成功");
    }

    @ApiOperation(value = "获取所有库位信息", notes = "获取所有库位信息")
    @GetMapping(value = "getLgortsFromDic")
    public ResultBody getLgortsFromDic(@RequestParam(required = false) Map params) {
        return ResultBody.ok().data(pmsApiUtil.getLgortsFromDic());
    }
}
